<script setup lang="tsx">
import { ContentWrap } from '@/components/ContentWrap'
import { useI18n } from '@/hooks/web/useI18n'
import { Table } from '@/components/Table'
import { unref, ref, reactive } from 'vue'
import { Search } from '@/components/Search'
import Write from '../FacOutComponents/EditFacOut.vue'
import { useTable } from '@/hooks/web/useTable'
import { BaseButton } from '@/components/Button'
import { Dialog } from '@/components/Dialog'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { Icon } from '@/components/Icon'
import { ProducerLedgerType } from '@/api/equip/type'
import ProducerLedgerApi from '@/api/equip/producerLedger'
import { useDictStore } from '@/store/modules/dictData'
const { t } = useI18n()
const saveLoading = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('添加')
const actionType = ref('')
const FormDisabled = ref(false)
const writeRef = ref()
const searchParams = ref({})
const currentRow = ref<ProducerLedgerType | null>(null)
const delLoading = ref(false)
const ids = ref<string[]>([])
const DictStore = useDictStore()
DictStore.setDict('producer_type') //厂商类型
DictStore.setDict('producer_rating') //评级
//表格操作
const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { currentPage, pageSize } = tableState
    const res = await ProducerLedgerApi.GetProducerLedger({
      pageNum: unref(currentPage),
      pageSize: unref(pageSize),
      ...unref(searchParams)
    })
    return {
      list: res.rows,
      total: res.total
    }
  },
  fetchDelApi: async () => {
    const res = await ProducerLedgerApi.DeletProducerLedger(unref(ids)[0])
    return !!res
  }
})
//表格结构
const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'index',
    label: t('tableDemo.index'),
    fixed: 'left',
    type: 'index',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    }
  },

  {
    field: 'producerName',
    label: t('厂商名称'),
    width: 150,
    search: {
      hidden: false,
      component: 'Input',
      componentProps: {
        placeholder: '厂商名称'
      }
    },
    form: {
      component: 'Input',
      colProps: {
        span: 20
      }
    }
  },
  {
    field: 'producerIntro',
    label: t('厂商简称'),
    width: 150,
    search: {
      hidden: true
    },
    form: {
      component: 'Input',
      colProps: {
        span: 20
      }
    }
  },
  {
    field: 'state',
    label: t('状态'),
    search: {
      hidden: true
    },
    formatter: (_: Recordable, __: any, cellValue: number) => {
      return cellValue == 0 ? '启用' : '禁用'
    },
    form: {
      component: 'RadioGroup',
      colProps: {
        span: 20
      },
      componentProps: {
        options: [
          {
            label: '启用',
            value: 0
          },
          {
            label: '禁用',
            value: 1
          }
        ]
      }
    }
  },
  {
    field: 'type',
    label: t('厂商类型'),
    formatter: (_: Recordable, __: any, cellValue: string) => {
      return DictStore.$state.producer_type?.map((item) => {
        if (item.dictValue == cellValue) {
          return item.dictLabel
        }
      })
    },
    form: {
      component: 'Select',
      colProps: {
        span: 20
      },
      componentProps: {
        options: DictStore.$state.producer_type?.map((item) => {
          return {
            label: item.dictLabel,
            value: item.dictValue
          }
        })
      }
    },
    search: {
      hidden: false,
      component: 'Select',
      componentProps: {
        placeholder: '厂商类型',
        options: DictStore.$state.producer_type?.map((item) => {
          return {
            label: item.dictLabel,
            value: item.dictValue
          }
        })
      }
    }
  },
  {
    field: 'rating',
    label: t('评级'),
    width: 100,
    formatter: (_: Recordable, __: any, cellValue: string) => {
      return DictStore.$state.producer_rating?.map((item) => {
        if (item.dictValue == cellValue) {
          return item.dictLabel
        }
      })
    },
    form: {
      component: 'Select',
      colProps: {
        span: 20
      },
      componentProps: {
        options: DictStore.$state.producer_rating?.map((item) => {
          return {
            label: item.dictLabel,
            value: item.dictValue
          }
        })
      }
    },
    search: {
      hidden: false,
      component: 'Select',
      componentProps: {
        placeholder: '评级',
        options: DictStore.$state.producer_rating?.map((item) => {
          return {
            label: item.dictLabel,
            value: item.dictValue
          }
        })
      }
    }
  },
  {
    field: 'userOne',
    label: t('联系人1'),
    width: 100,
    search: {
      hidden: true
    },
    form: {
      component: 'Input',
      colProps: {
        span: 20
      }
    }
  },
  {
    field: 'phoneOne',
    label: t('联系人1电话'),
    width: 150,
    search: {
      hidden: true
    },
    form: {
      component: 'Input',
      colProps: {
        span: 20
      }
    }
  },
  {
    field: 'userTwo',
    label: t('联系人2'),
    width: 100,
    search: {
      hidden: true
    },
    form: {
      component: 'Input',
      colProps: {
        span: 20
      }
    }
  },
  {
    field: 'phoneTwo',
    label: t('联系人2电话'),
    width: 150,
    search: {
      hidden: true
    },
    form: {
      component: 'Input',
      colProps: {
        span: 20
      }
    }
  },
  {
    field: 'createBy',
    label: t('创建人'),
    width: 100,
    search: {
      hidden: true
    },
    form: {
      component: 'Input',
      colProps: {
        span: 20
      }
    }
  },
  {
    field: 'address',
    label: t('地址'),
    width: 150,
    search: {
      hidden: true
    },
    form: {
      component: 'Input',
      colProps: {
        span: 20
      }
    }
  },
  {
    field: 'action',
    label: '操作',
    width: 150,
    fixed: 'right',
    form: {
      hidden: true
    },
    search: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    slots: {
      default: (data) => {
        return (
          <>
            <span class="TableBtn" onClick={() => action(data.row, 'Detail')}>
              查看
            </span>
            <span class="TableBtn" onClick={() => action(data.row, 'edit')}>
              修改
            </span>
            <span class="TableBtn" style="color:#f56c6c" onClick={() => delData(data.row)}>
              删除
            </span>
          </>
        )
      }
    }
  }
])
//表格操作
const action = (row: ProducerLedgerType, type: string) => {
  actionType.value = type
  dialogVisible.value = true
  if (type == 'add') {
    currentRow.value = {}
    dialogTitle.value = '添加'
    FormDisabled.value = false
  } else if (type == 'edit') {
    dialogTitle.value = '修改'
    FormDisabled.value = false
    currentRow.value = row
  } else {
    dialogTitle.value = '详情'
    FormDisabled.value = true
    currentRow.value = row
  }
}
const { loading, dataList, total, currentPage, pageSize } = tableState
const { getList, getElTableExpose, delList } = tableMethods
const { allSchemas } = useCrudSchemas(crudSchemas)
//删除轨迹
const delData = async (row: ProducerLedgerType) => {
  const elTableExpose = await getElTableExpose()
  ids.value = row ? [row.uuid] : elTableExpose?.getSelectionRows().map((v: any) => v.uuid) || []
  delLoading.value = true
  await delList(unref(ids).length).finally(() => {
    delLoading.value = false
  })
}
const save = async () => {
  const write = unref(writeRef)
  const formData = await write?.submit()
  if (formData) {
    saveLoading.value = true
    saveLoading.value = false
    const res: any = ref(false)
    //新增任务组
    if (actionType.value == 'add') {
      res.value = await ProducerLedgerApi.AddProducerLedger(formData)
        .catch(() => {})
        .finally(() => {
          saveLoading.value = false
        })
    } else {
      //修改字
      res.value = await ProducerLedgerApi.EditProducerLedger(formData)
        .catch(() => {})
        .finally(() => {
          saveLoading.value = false
        })
    }
    if (res.value) {
      dialogVisible.value = false
      currentPage.value = 1
      getList()
    }
  }
}
const setSearchParams = (params: any) => {
  currentPage.value = 1
  searchParams.value = params
  getList()
}
</script>

<template>
  <ContentWrap title="厂商台账">
    <!-- <div class="flex"> -->
    <BaseButton size="small" type="primary" @click="action({}, 'add')" class="AddbtnStyle">
      <Icon icon="ep:plus" :size="13" />新增
    </BaseButton>
    <Search :schema="allSchemas.searchSchema" @reset="setSearchParams" @search="setSearchParams" />
    <!-- </div> -->
    <Table
      v-model:pageSize="pageSize"
      v-model:currentPage="currentPage"
      :columns="allSchemas.tableColumns"
      :data="dataList"
      row-key="id"
      :loading="loading"
      sortable
      :pagination="{
        total: total
      }"
      @register="tableRegister"
    />
  </ContentWrap>
  <Dialog style="width: 500px" v-model="dialogVisible" :title="dialogTitle">
    <Write
      ref="writeRef"
      :form-schema="allSchemas.formSchema"
      :current-row="currentRow"
      :FormDisabled="FormDisabled"
    />
    <template #footer>
      <BaseButton type="primary" :loading="saveLoading" @click="save">
        {{ t('提交') }}
      </BaseButton>
      <BaseButton @click="dialogVisible = false">{{ t('关闭') }}</BaseButton>
    </template>
  </Dialog>
</template>

<style scoped>
:deep(.TableBtn) {
  margin: 0 5px;
  font-size: 12px;
  cursor: pointer;
  color: #409eff;
  font-weight: 600 !important;
}
.AddbtnStyle {
  margin-bottom: 18px;
  margin-right: 10px;
}
</style>
